
import axios from 'axios'
import Store from "@/store"
import {
	Message
} from "element-ui"
import Router from "@/router"
import Vue from 'vue'
import qs from 'qs'
import {removeLocalData} from '@/common/utils'

axios.defaults.timeout = 20000; //响应时间
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';        //配置请求头
axios.defaults.baseURL = HX_BASEURL; //配置接口地址



//POST传参序列化(添加请求拦截器)
axios.interceptors.request.use((config) => {
	//在发送请求之前做某件事
	if (config.headers["Content-Type"] == "multipart/form-data") {
		// let fromData = new FormData(); 
	 //    fromData.append('file',file);
	}
	// console.log(Router);
	// console.log(Vue.route);
	
	
	if (Store.state.user.userInfo && config.url !="/login") {
		config.headers['X-TOKEN'] = Store.state.user.userInfo.token;
	}
	return config;
}, (error) => {
	console.log('错误的传参')
	return Promise.reject(error);
});

//返回状态判断(添加响应拦截器)
axios.interceptors.response.use((res) => {
	//对响应数据做些事
	if (res.headers["content-type"].indexOf("application/json") != -1) {
		//90040015 为上传格式校验失败的返回码
		if (res.data.code == 200 || res.data.code == 90040015) {
			return res.data.result;
		} else if (res.data.code == 405 || res.data.code == 409) {
			removeLocalData("userInfo");
			removeLocalData("authList");
			Message.error("登录过期");
			setTimeout(() => {
				Router.push({
					name: "Login"
				})
			}, 500)
		} else {
			Message.error(res.data.message)
		}
	} else {
		if (res.data.code) {
			Message.error(res.data.message)
		} else {
			return res
		}
	}

}, (error) => {
	console.log(error)
	Message.error(error.response.data)
	return Promise.reject(error);
});

//返回一个Promise(发送post请求)
export const fetchPost = (url, params = {}) =>{
	return axios.post(url, params);
}
////返回一个Promise(发送get请求)
export const fetchGet = (url, params = {}) =>{
	return axios.get(url, {
		params: params
	})
}
//下载文件
export const downLoad = (url, params = {}) =>{
	return new Promise((resolve, reject) => {
		axios.get(url, {
			params: params,
			responseType: 'blob'
		})
		.then(res => {
			let fileName;
			let reader = new FileReader();
			let data = res.data;
			reader.onload = e => {
				if (e.target.result.indexOf('Result') != -1 && JSON.parse(e.target.result).Result == false) {
					// 进行错误处理
				} else {
					if (!fileName) {
						let contentDisposition = res.headers['content-disposition'];
						if (contentDisposition) {
							fileName = window.decodeURI(res.headers['content-disposition'].split('=')[1], "UTF-8");
						}
					}
					executeDownload(data, fileName);
				}
			};
			reader.readAsText(data);
			resolve(res.data);
		}, err => {
			reject(err)
		})
		.catch((error) => {
			reject(error)
		})
	});
}


//  模拟点击a 标签进行下载
function executeDownload(data, fileName) {
	if (!data) {
		return
	}
	let url = window.URL.createObjectURL(new Blob([data]));
	let link = document.createElement('a');
	link.style.display = 'none';
	link.href = url;
	link.setAttribute('download', fileName);
	document.body.appendChild(link);
	link.click();
	document.body.removeChild(link);
}

export const upload = (url,params = {},headers = {}) =>{
	return axios.post(url,params, {
		headers: Object.assign({
			'Content-Type': 'multipart/form-data'
		}, headers)
	})
}
export default {
	fetchPost,
	fetchGet,
	downLoad,
	upload
}
